package com.maixun.lib_comment.ui.dialog

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.maixun.lib_base.ui.dialog.BaseDialogImpl
import com.maixun.lib_base.utils.ScreenUtils
import com.maixun.lib_comment.R
import com.maixun.lib_comment.entity.PhoneBeen
import com.maixun.lib_comment.recyclerview.BaseAdapter
import com.maixun.lib_comment.recyclerview.ViewHolderImpl
import kotlinx.android.synthetic.main.comment_dialog_phone.view.*

/**
 * 作者：Lmoumou
 * 时间：2020/9/4 15:31
 */
class PhoneDialog : BaseDialogImpl() {
    override fun getLayoutId(): Int = R.layout.comment_dialog_phone

    override fun getDialogWith(): Int {
        return (ScreenUtils.getScreenWidth(mContext) * 0.7).toInt()
    }

    private val dataList by lazy { mutableListOf<PhoneBeen>() }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        initData()

        view.mRecyclerView.adapter = object : BaseAdapter<PhoneBeen>(mContext, dataList) {
            override fun itemViewType(position: Int): Int = R.layout.comment_item_pone

            override fun bindData(holder: ViewHolderImpl, position: Int) {
                dataList[position].run {
                    holder.getView<View>(R.id.line).visibility =
                        if (position + 1 == dataList.size) View.GONE else View.VISIBLE
                    holder.setText(R.id.mTextView, phoneNum)
                    val ivSelect = holder.getView<ImageView>(R.id.ivSelect)
                    ivSelect.visibility = if (isSelect) View.VISIBLE else View.GONE
                    holder.itemView.setOnClickListener {
                        selectAll(dataList, false)
                        this.isSelect = true
                        notifyDataSetChanged()
                    }
                }
            }

            private fun selectAll(dataList: MutableList<PhoneBeen>, isSelect: Boolean) {
                dataList.forEach {
                    it.isSelect = isSelect
                }
            }
        }

        view.tvCancel.setOnClickListener {
            dismissThis(isResumed)
        }
        view.tvSure.setOnClickListener {
            callPhone()
            dismissThis(isResumed)
        }
    }

    private fun callPhone() {
        dataList.find {
            it.isSelect
        }?.apply {
            val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:${phoneNum}"))
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }
    }

    private fun initData() {
        dataList.clear()
        dataList.add(PhoneBeen(resources.getString(R.string.comment_coustomer_phone), true))
    }
}